package it.trekker.activities;

import java.util.ArrayList;
import java.util.List;
import it.trekker.R;
import it.trekker.adapter.PoiAdapter;
import it.trekker.dataexchange.PoiRealTimeInfo;
import it.trekker.db.ExcursionTableMeta;
import it.trekker.db.Poi;
import it.trekker.db.PoiDAO;
import it.trekker.gps.service.GPSLocationService;
import it.trekker.statistics.PoiDistanceStatistics;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;


public class DistanceToPoiActivity extends ListActivity {

	private static final String TAG = DistanceToPoiActivity.class.getSimpleName();

	// GUI components
	private PoiAdapter poiAdapter = null;
	private List<PoiRealTimeInfo> pois = null;

	private SharedPreferences sharedPref = null;

	// Service components
	private GPSLocationService gpsLocationService = null;
	private PoiDistanceStatistics poiDistanceStatistics = null;	// Shared RealTimeStatistics (shared with ExcursionMainActivity) 
	private ServiceConnection gpsServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			gpsLocationService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			gpsLocationService = ((GPSLocationService.GPSBinder)service).getService();
			//			gpsLocationService.addGPSListener(poiDistanceStatistics);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		loadPreferences();

		pois = new ArrayList<PoiRealTimeInfo>();

		// Shared RealTimeStatistics (shared with ExcursionMainActivity) 
		poiDistanceStatistics = PoiDistanceStatistics.getSharedInstance();
		poiDistanceStatistics.registerDistanceToPoiCallback(poiDistanceCallback);

		loadPoiList();
		poiAdapter = new PoiAdapter(this, R.layout.distancepoi_listview_row, pois, poiDistanceStatistics);
		setListAdapter(poiAdapter);

		Intent gpsIntent = new Intent(this, GPSLocationService.class);
		getApplicationContext().bindService(gpsIntent, gpsServiceConnection, Context.BIND_AUTO_CREATE);
		
		registerForContextMenu(getListView());


		//		GPSCoordinate coord = new GPSCoordinate();
		//		coord.setLatitude(10.0123456);
		//		coord.setLongitude(45.0123456);
		//		Poi poi = new Poi();
		//		poi.setFriendlyName("Poi1");
		//		poi.setLocation(coord);
		////		pois.add(poi);
		//		poiDistanceStatistics.addPoi(poi, 100);
		//		coord.setLatitude(11.0123456);
		//		coord.setLongitude(43.0123456);
		//		poi = new Poi();
		//		poi.setFriendlyName("Poi2");
		//		poi.setLocation(coord);
		////		pois.add(poi);
		//		poiDistanceStatistics.addPoi(poi, 500);


	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		getApplicationContext().unbindService(gpsServiceConnection);
		poiDistanceStatistics.removeDistanceToPoiCallback(poiDistanceCallback);
	}

	// Back key pression handled by the parent (ExcursionMainActivity tabactivity)
	@Override 
	public void onBackPressed() { 
		this.getParent().onBackPressed();
	}

	//	@Override
	//	public void onConfigurationChanged(Configuration newConfig) {
	//		super.onConfigurationChanged(newConfig);
	//	}





	//**********************************************************//
	//********************** Context Menu **********************//
	//**********************************************************//

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;

		String poiName = pois.get(info.position).getPoi().getFriendlyName();

		menu.setHeaderTitle(poiName);

		String[] menuItems = getResources().getStringArray(R.array.poi_contextmenu);		
		for (int i = 0; i<menuItems.length; i++) {
			menu.add(Menu.NONE, i, i, menuItems[i]);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		int menuItemIndex = item.getItemId();
		PoiRealTimeInfo poiRealTimeInfo = pois.get(info.position);
		
		switch(menuItemIndex) {

			case 0:		// Delete
				deletePoi(poiRealTimeInfo);
				break;
			}

		return true;
	}





	//***********************************************************************//
	//*************************** Utility methods ***************************//
	//***********************************************************************//


	private void loadPreferences() {
		sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
	}


	private void loadPoiList() {
		for(PoiRealTimeInfo poi : poiDistanceStatistics.getPoisList()) {
			if(!pois.contains(poi))
				pois.add(poi);
		}
	}

	
	private void deletePoi(PoiRealTimeInfo poiRealTimeInfo) {
		PoiDistanceStatistics.getSharedInstance().removePoi(poiRealTimeInfo.getPoi());
		PoiDAO poiDAO = new PoiDAO(this);
		poiDAO.open();
		poiDAO.deletePoi(poiRealTimeInfo.getPoi().getId());
		poiDAO.close();
		pois.remove(poiRealTimeInfo);

		poiAdapter.notifyDataSetChanged();
	}




	//**********************************************************************//
	//************ Callback and message handler to update views ************//
	//**********************************************************************//


	private PoiDistanceStatistics.IDistanceToPoiCallback poiDistanceCallback = new PoiDistanceStatistics.IDistanceToPoiCallback() {

		@Override
		public void distanceToPoiChanged(List<PoiRealTimeInfo> distances) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					//			getListView().invalidateViews();
					poiAdapter.notifyDataSetChanged();
				}
			});
		}

		@Override
		public void newPoiAdded(final PoiRealTimeInfo poi) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					pois.add(poi);
					poiAdapter.notifyDataSetChanged();
				}
			});
		}
	};
}
